package com.ruoyi.supervision.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.scene.domain.SceneInspectionIssue;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.util.HandleFileUtil;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.RequiredArgsConstructor;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import com.ruoyi.supervision.domain.bo.SupervisionLogBo;
import com.ruoyi.supervision.domain.vo.SupervisionLogVo;
import com.ruoyi.supervision.domain.SupervisionLog;
import com.ruoyi.supervision.mapper.SupervisionLogMapper;
import com.ruoyi.supervision.service.ISupervisionLogService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 监理日志Service业务层处理
 *
 * @author llb
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class SupervisionLogServiceImpl implements ISupervisionLogService {

    private final SupervisionLogMapper baseMapper;

    private final ISysOssService sysOssService;

    /**
     * 查询监理日志
     */
    @Override
    public SupervisionLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询监理日志列表
     */
    @Override
    public TableDataInfo<SupervisionLogVo> queryPageList(SupervisionLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SupervisionLog> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(SupervisionLog::getRq);
        Page<SupervisionLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<SupervisionLogVo> records = result.getRecords();
        if(CollUtil.isNotEmpty(records)) {
            records.stream().forEach(e -> {
                //附件
                String fileId = e.getFileId();
                if (ObjectUtils.isNotEmpty(fileId)){
                    String[] split = fileId.split(",");
                    Long[] fileIds =(Long[]) ConvertUtils.convert(split,Long.class);
                    List<SysOssVo> sysOssVos = sysOssService.listByIds(Arrays.asList(fileIds));
                    e.setOssVoList(sysOssVos);
                }
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询监理日志列表
     */
    @Override
    public List<SupervisionLogVo> queryList(SupervisionLogBo bo) {
        LambdaQueryWrapper<SupervisionLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SupervisionLog> buildQueryWrapper(SupervisionLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SupervisionLog> lqw = Wrappers.lambdaQuery();
        if(bo.getAllProject()==null||"false".equals(bo.getAllProject())){
            lqw.eq(bo.getProjectId() != null, SupervisionLog::getProjectId, bo.getProjectId());
        }
        lqw.eq(StringUtils.isNotBlank(bo.getJljg()), SupervisionLog::getJljg, bo.getJljg());
        lqw.eq(StringUtils.isNotBlank(bo.getBh()), SupervisionLog::getBh, bo.getBh());
        lqw.eq(StringUtils.isNotBlank(bo.getLlr()), SupervisionLog::getLlr, bo.getLlr());
        lqw.eq(StringUtils.isNotBlank(bo.getShry()), SupervisionLog::getShry, bo.getShry());
        lqw.between(params.get("beginRq") != null && params.get("endRq") != null,
            SupervisionLog::getRq ,params.get("beginRq"), params.get("endRq"));
        lqw.eq(StringUtils.isNotBlank(bo.getTqqk()), SupervisionLog::getTqqk, bo.getTqqk());
        lqw.eq(StringUtils.isNotBlank(bo.getZysgqk()), SupervisionLog::getZysgqk, bo.getZysgqk());
        lqw.eq(StringUtils.isNotBlank(bo.getJlzygz()), SupervisionLog::getJlzygz, bo.getJlzygz());
        lqw.eq(StringUtils.isNotBlank(bo.getWtjclqk()), SupervisionLog::getWtjclqk, bo.getWtjclqk());
        lqw.eq(StringUtils.isNotBlank(bo.getFileId()), SupervisionLog::getFileId, bo.getFileId());
        return lqw;
    }

    /**
     * 新增监理日志
     */
    @Override
    public Boolean insertByBo(SupervisionLogBo bo) {
        SupervisionLog add = BeanUtil.toBean(bo, SupervisionLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改监理日志
     */
    @Override
    public Boolean updateByBo(SupervisionLogBo bo) {
        SupervisionLog update = BeanUtil.toBean(bo, SupervisionLog.class);
        validEntityBeforeSave(update);
        //先删除本次修改删掉的附件；
        Set<Long> fileNoOld = bo.getFileNoOld();
        Set<Long> fileNos = bo.getFileNos();
        Set<Long> deleteFiles;
        if(CollUtil.isNotEmpty(fileNoOld)){
            if(CollUtil.isEmpty(fileNos)){
                deleteFiles = fileNoOld;
            } else {
                deleteFiles = fileNoOld.stream().filter(e-> !fileNos.contains(e)).collect(Collectors.toSet());
            }
            if(CollUtil.isNotEmpty(deleteFiles)){
                sysOssService.deleteWithValidByIds(deleteFiles,true);
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SupervisionLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除监理日志
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 导出监理日志详情单
     *
     * @param response
     * @param bo
     */
    @Override
    public void exportLog(HttpServletResponse response, SupervisionLogBo bo, String type) {
        SupervisionLogVo vo = queryById(bo.getId());
        // 日期处理
        if (ObjectUtil.isNotEmpty(vo) && ObjectUtil.isNotEmpty(vo.getRq())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(vo.getRq());
            vo.setRqFormat(format);
        }
        // 指定word模板
        InputStream wordTemplate = HandleFileUtil.getWordTemplate("excel/监理日志.docx");
        // 设置word内容
        Map<String, Object> finalMap = new HashMap<>();
        List<Object> workList = new ArrayList<>();
        finalMap.put("workList", workList);

        finalMap.put("projectName", vo.getProjectName());
        finalMap.put("bh", vo.getBh());
        finalMap.put("jljg", vo.getJljg());
        finalMap.put("llr", vo.getLlr());
        finalMap.put("shry", vo.getShry());
        finalMap.put("rq", vo.getRqFormat());
        finalMap.put("tqqk", vo.getTqqk());
        finalMap.put("zysgqk", vo.getZysgqk());
        finalMap.put("jlzygz", vo.getJlzygz());
        finalMap.put("wtjclqk", vo.getWtjclqk());

        if ("WORD".equals(type)) {
            HandleFileUtil.writeToWord(response, wordTemplate, finalMap);
        }
        if ("PDF".equals(type)) {
            HandleFileUtil.writeToPdf(response, wordTemplate, finalMap);
        }
    }
}
